<script setup lang="ts">
import {defineProps, onBeforeMount, onMounted, reactive, ref} from 'vue'
import {deLete, get, post_json,post} from '@/assets/ts/ruquestMethod'
import type {AddressData, Address, Account} from "@/assets/ts/Interfaces";
import { pcaTextArr } from 'element-china-area-data'
import {ElMessage} from "element-plus";
import type {FormRules} from "element-plus"
import {Cellphone, Message} from "@element-plus/icons-vue";
const props = defineProps({
    username : String
})
const options = pcaTextArr
const dialogVisible = ref(false)
const dialogEmail = ref(false)
const value = reactive({
  region:'',
  fullAddress:'',
  username:'',
  isInput: false
})
const ruleForm = reactive({
  email : '',
  code : ''
})
let time = 0, timer: number | undefined
const validEmail = (rule: any, value: any, callback: any)=>{
  if(value == '')
    callback(new Error('请输入邮箱'))
  else if(!/^[A-Za-z0-9\u4e00-\u9fa5]+@[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)+$/.test(value))
    callback(new Error('请输入格式正确的邮箱'))
  else {
    isValidPhone.value = true
    callback()
  }
}
const rules = reactive<FormRules>({
  email: [{validator: validEmail,trigger:['blur','change']}]
})
const isValidPhone = ref(false)
let codeValid = reactive({
  phoneValid : false,
  timeout : false,
  buttonText: '获取验证码'
})
let addresses = reactive<AddressData>({
    data : [{
        id : 0,
        username : '',
        name : '',
        province : '',
        city : '',
        district : '',
        address : ''
    }]
})
let account = reactive<Account>({
    userid : '',
    email : '',
    phone : '',
    password : ''
})
const getAddress = () =>{
    get('/addresses',
        (data:any) =>{
            addresses.data = data.data
    })
}
const getAccount = () => {
    get('/accounts/islogin',
        (data :any) =>{
            account.userid = data.data.userid
            account.email = data.data.email
            account.password = data.data.password
            account.phone = data.data.phone
            console.log(account)
        }
    )
}
const handleDelete = (index: number, row: Address) => {
 deLete(`/addresses/${row.id}`,(res:any)=>{
   console.log(res)
   getAddress()
 })
}
const handleAddress = ()=> {
  value.isInput = true
  console.log(value.region)
}
const insertAddress = ()=>{
  if(value.username == '' || value.fullAddress == ''){
    ElMessage.warning('请输入全部信息')
    return
  }
  post_json('/addresses',{
    name: value.username,
    province:value.region[0],
    city:value.region[1],
    district:value.region[2],
    address:value.fullAddress
  },(res:any)=>{
    getAddress()
    dialogVisible.value = false
  })
}
function timer1(){
  if(time > 0){
    time--
    codeValid.buttonText = time +'s后重新获取'
    timer = setTimeout(timer1,1000)
  }else {
    time = 0
    codeValid.buttonText = '获取验证码'
    codeValid.timeout = false
    clearTimeout(timer)
  }
}
const sendEmail = ()=>{
  post('/accounts/sendEmail',{
        email: ruleForm.email
      },
      (data:any) => {
        if(data.status === 1){
          ElMessage.success(data.message)
          codeValid.timeout = true
          time = 60
          timer1()
        }
        if(data.status === 0){
          ElMessage.warning(data.message)
        }
      }
  )
}
const addEmail = ()=>{
  post('/accounts/addEmail',{
      email: ruleForm.email,
      code: ruleForm.code
  },()=>{
    dialogEmail.value = false
    getAccount()
  })
}
onBeforeMount(() =>{
    getAddress()
    getAccount()
})
</script>

<template>
  <el-descriptions
      title="用户信息"
      direction="vertical"
      :column="4"
      border
  >
    <el-descriptions-item label="用户名">{{ account.userid }}</el-descriptions-item>
    <el-descriptions-item label="手机号">{{ account.phone }}</el-descriptions-item>
    <el-descriptions-item label="密码">
        <span>**********</span>
    </el-descriptions-item>
    <el-descriptions-item label="邮箱">
        <span v-if="account.email == null">您还没有设置邮箱哦。点击<el-link @click="dialogEmail = true">这里</el-link>进行邮箱绑定</span>
        <span v-else>{{account.email}}</span>
    </el-descriptions-item>
  </el-descriptions>
 <h2>用户地址</h2>
  <el-button class="insert-address" type="primary" @click="dialogVisible = true">添加地址</el-button>
 <el-table stripe :data="addresses.data" style="width: 100%">
     <el-table-column prop="name" label="姓名" width="120" />
     <el-table-column label="地址信息">
         <el-table-column prop="province" label="省" width="120" />
         <el-table-column prop="city" label="市" width="120" />
         <el-table-column prop="district" label="区" width="120"/>
         <el-table-column prop="address" label="具体地址"  />
     </el-table-column>
  <el-table-column label="操作">
   <template #default="scope">
    <el-button
        size="small"
        type="danger"
        @click="handleDelete(scope.$index, scope.row)"
    >删除</el-button
    >
   </template>
  </el-table-column>
 </el-table>
  <el-dialog
      v-model="dialogVisible"
      title="添加收货地址"
      width="30%"
  >
    <div>姓名</div>
    <el-input v-model="value.username" style="width: 200px" ></el-input>
    <div>所在地区</div>
    <el-cascader v-model="value.region" :options="options" @change="handleAddress"/>
    <div>详细地址</div>
    <el-input v-model="value.fullAddress" style="width: 200px" :disabled="!value.isInput"></el-input>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="insertAddress">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog
      v-model="dialogEmail"
      title="绑定邮箱"
      width="30%"
  >
    <el-form :label-position="'top'" :rules="rules" :model="ruleForm">
      <el-form-item label="邮箱" prop="email">
        <el-input  type="text" v-model="ruleForm.email" clearable>
          <template #prefix>
            <el-icon><Cellphone /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="验证码">
        <div>
          <el-row>
            <el-col :span="16">
              <el-input type="text" v-model="ruleForm.code" style="width: 200px">
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-col>
            <el-col :span="8">
              <el-button style="width: 100px;" :disabled="!isValidPhone||codeValid.timeout" @click="sendEmail">获取验证码</el-button>
            </el-col>
          </el-row>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogEmail = false">取消</el-button>
        <el-button type="primary" @click="addEmail">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>

<style scoped>
.insert-address{
  margin: 10px 0;
}
</style>